package com.xyhuo.leetcode.y2025;

import java.util.ArrayList;
import java.util.List;

public class Calculate {
    public int calculate(String s) {
        int index = 0;
        char[] charArray = s.toCharArray();
        List<Integer> list = new ArrayList<>();
        List<String> signList = new ArrayList<>();
        for (int i = 0; i < charArray.length; i++) {
            if (charArray[i] == '+' || charArray[i] == '-' || charArray[i] == '*' || charArray[i] == '/') {
                String num = s.substring(index, i).replaceAll(" ", "");
                index = i + 1;
                deal(signList, list, Integer.valueOf(num), String.valueOf(charArray[i]));
            }
        }
        deal(signList, list, Integer.valueOf(s.substring(index).replaceAll(" ", "")), null);

        int ans = list.get(0);
        int listIndex = 1;
        for (int i = 0; i < signList.size(); i++) {
            if ("+".equals(signList.get(i))) {
                ans += list.get(listIndex++);
            } else if ("-".equals(signList.get(i))) {
                ans -= list.get(listIndex++);
            }
        }
        return ans;
    }


    private void deal(List<String> signList, List<Integer> list, Integer num, String sign) {
        if (signList.isEmpty()) {
            if (null != sign) {
                signList.add(sign);
            }
            list.add(num);
            return;
        }
        String lastSign = signList.get(signList.size() - 1);
        Integer value = num;
        if ("*".equals(lastSign)) {
            Integer lastNum = list.get(list.size() - 1);
            value = lastNum * num;
            list.remove(list.size() - 1);
            signList.remove(signList.size() - 1);

        } else if ("/".equals(lastSign)) {
            Integer lastNum = list.get(list.size() - 1);
            value = lastNum / num;
            list.remove(list.size() - 1);
            signList.remove(signList.size() - 1);

        }
        if (null != sign) {
            signList.add(sign);
        }
        list.add(value);
    }

    public static void main(String[] args) {
        Calculate c = new Calculate();
//        c.calculate("31+22*2+4/2+1");
        c.calculate(" 3/2 ");
    }
}
